import { Form, Input, InputNumber, Select } from "antd"
import { useComponentStore } from "../../stores/components"
import { ComponentSetter, useComponentConfigStore } from "../../stores/component-config"
import { CSSProperties, useEffect, useState } from "react"
import CssEditor from "./CssEditor"
import { debounce } from "lodash-es"
import styleToObject from 'style-to-object'


const ComponentStyle: React.FC = () => {

  const [form] = Form.useForm()

  const { curComponentId, curComponent, updateComponentStyles } = useComponentStore()
  const { componentConfig } = useComponentConfigStore()

  const [css, setCss] = useState<string>(`.comp{\n\n}`)

  useEffect(() => {
    form.resetFields()

    const data = form.getFieldsValue()
    form.setFieldsValue({ ...data, ...curComponent?.styles })

    setCss(toCSSStr(curComponent?.styles!))
  }, [curComponent])

  function toCSSStr(css: Record<string, any>) {
    let str = `.comp {\n`;
    for (let key in css) {
      let value = css[key];
      if (!value) {
        continue;
      }
      if (['width', 'height'].includes(key) && !value.toString().endsWith('px')) {
        value += 'px';
      }

      str += `\t${key}: ${value};\n`
    }
    str += `}`;
    return str;
  }

  if (!curComponentId || !curComponent) return null

  function renderFormElement(setting: ComponentSetter) {
    const { type, options } = setting

    if (type === 'select') {
      return <Select options={options} style={{width: '90%'}} />
    } else if (type === 'input') {
      return <Input style={{width: '90%'}} />
    } else if (type === 'inputNumber') {
      return <InputNumber style={{width: '90%'}} />
    }
  }

  function valuesChange(changeValues: CSSProperties) {
    if (curComponentId) {
      updateComponentStyles(curComponentId, changeValues)
    }
  }

  const handleEditorChange = debounce((value) => {
    setCss(value)

    let css: Record<string, any> = {}

    try {
      const cssStr = value.replace(/\/\*.*\*\//, '')
        .replace(/(\.?[^{]+{)/, '')
        .replace('}', '');

      styleToObject(cssStr, (name, value) => {
        css[name.replace(/-\w/, (item) => item.toUpperCase().replace('-', ''))] = value;
      });

      console.log(css);
      updateComponentStyles(curComponentId, { ...form.getFieldsValue(), ...css }, true)
    } catch (e) { }
  }, 500)

  return (
    <Form
      form={form}
      onValuesChange={valuesChange}
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 14 }}>
      {
        componentConfig[curComponent.name]?.stylesSetter?.map(setter => (
          <Form.Item key={setter.name} name={setter.name} label={setter.label}>
            {renderFormElement(setter)}
          </Form.Item>
        ))
      }
      <div className='h-[200px] border-[1px] border-[#ccc]'>
        <CssEditor value={css} onChange={handleEditorChange} />
      </div>
    </Form>
  )
}

export default ComponentStyle